﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using WeLinkHelper.Model;
using WeLinkHelper.Untils.Ext;

namespace WeLinkHelper.Untils
{
    public class WebRequestHelper
    {
        #region 公共方法
        /// <summary>
        /// Get数据接口
        /// </summary>
        /// <param name="getUrl">接口地址</param>
        /// <returns></returns>
        public static string GetWebRequest(string getUrl)
        {
            string responseContent = "";

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(getUrl);
            request.ContentType = "application/json";
            request.Method = "GET";

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            //在这里对接收到的页面内容进行处理
            using (Stream resStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
                {
                    responseContent = reader.ReadToEnd().ToString();
                }
            }
            return responseContent;
        }

        /// <summary>
        /// PUT数据接口
        /// </summary>
        /// <param name="putUrl">接口地址</param>
        /// <returns></returns>
        public static string PutWebRequest(string putUrl, string paramData, WebHeaderCollection headerCollection = null)
        {
            string responseContent = string.Empty;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData);   //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(putUrl));
                webReq.Method = "PUT";
                webReq.ContentType = "application/json;charset=UTF-8";
                if (headerCollection != null)
                    webReq.Headers = headerCollection;
                webReq.ContentLength = byteArray.Length;
                using (Stream reqStream = webReq.GetRequestStream())
                {
                    reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    //reqStream.Close();
                }
                using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseContent = sr.ReadToEnd().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                WeLinkResultMsgModel msgModel = new WeLinkResultMsgModel();
                msgModel.error = new Error() { errorCode = "000001", errorMsg = ex.Message };
                return JsonConvert.SerializeObject(msgModel);
            }
            return responseContent;
        }
        /// <summary>
        /// Post数据接口
        /// </summary>
        /// <param name="postUrl">接口地址</param>
        /// <param name="paramData">提交json数据</param>
        /// <param name="dataEncode">编码方式(Encoding.UTF8)</param>
        /// <returns></returns>
        public static string PostWebRequest(string postUrl, string paramData, WebHeaderCollection headerCollection = null)
        {
            string responseContent = string.Empty;
            try
            {
                byte[] byteArray = Encoding.UTF8.GetBytes(paramData);   //转化
                HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(new Uri(postUrl));
                webReq.Method = "POST";
                webReq.ContentType = "application/json;charset=UTF-8";
                if (headerCollection != null)
                    webReq.Headers = headerCollection;
                webReq.ContentLength = byteArray.Length;
                using (Stream reqStream = webReq.GetRequestStream())
                {
                    reqStream.Write(byteArray, 0, byteArray.Length);//写入参数
                    //reqStream.Close();
                }
                using (HttpWebResponse response = (HttpWebResponse)webReq.GetResponse())
                {
                    //在这里对接收到的页面内容进行处理
                    using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                    {
                        responseContent = sr.ReadToEnd().ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                WeLinkResultMsgModel msgModel = new WeLinkResultMsgModel();
                msgModel.error = new Error() { errorCode = "000001", errorMsg = ex.Message };
                return JsonConvert.SerializeObject(msgModel);
            }
            return responseContent;
        }

        public static async Task<HttpResponseMessage> Upload(string imagePath, string token)
        {
            using (var httpClient = new HttpClient())
            {
                var formDataContent = new MultipartFormDataContent();
                byte[] fileBytes = await GetBytesFromUrlAsync(httpClient, imagePath);

                // 读取并将图像作为二进制数据添加到表单内容中
                ByteArrayContent imageContent = new ByteArrayContent(fileBytes);
                imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                formDataContent.Add(imageContent, "file", "filename.jpg");

                // 将Token作为Header添加到POST请求中
                httpClient.DefaultRequestHeaders.Add("Accept-Charset", "UTF-8");
                httpClient.DefaultRequestHeaders.Add("x-wlk-Authorization", token);
                HttpResponseMessage response = await httpClient.PostAsync("https://open.welink.huaweicloud.com/api/tinyimage/v2/images", formDataContent);
                return response;
            }
        }
        /// <summary>
        /// 云空间文件上传
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="url"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        public static async Task<HttpResponseMessage> CloudUpload(FileInfo fileInfo, string url, string token)
        {
            using (var httpClient = new HttpClient())
            {
                var formDataContent = new MultipartFormDataContent();
                byte[] fileBytes = File.ReadAllBytes(fileInfo.FullName); ;

                // 读取并将图像作为二进制数据添加到表单内容中
                ByteArrayContent imageContent = new ByteArrayContent(fileBytes);
                imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                formDataContent.Add(imageContent, "file", fileInfo.Name);

                // 将Token作为Header添加到POST请求中
                httpClient.DefaultRequestHeaders.Add("Accept-Charset", "UTF-8");
                httpClient.DefaultRequestHeaders.Add("x-wlk-Authorization", token);
                HttpResponseMessage response = await httpClient.PostAsync($"{url}?objectLength={fileInfo.Length}", formDataContent);
                return response;
            }
        }

        public static async Task<HttpResponseMessage> CloudUpload(byte[] fileBytes, string fileName, string url)
        {
            using (var httpClient = new HttpClient())
            {
                var formDataContent = new MultipartFormDataContent();

                // 读取并将图像作为二进制数据添加到表单内容中
                ByteArrayContent imageContent = new ByteArrayContent(fileBytes);
                imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                formDataContent.Add(imageContent, "file", fileName);
                // 将Token作为Header添加到POST请求中
                httpClient.DefaultRequestHeaders.Add("Accept-Charset", "UTF-8");
                HttpResponseMessage response = await httpClient.PostAsync($"{url}", formDataContent);
                return response;
            }
        }

        public static void uploadPart(string uploadUrl, FileInfo file)
        {
            //分块
            List<byte[]> li = LimitedSizeInputStream(file, 10485760);
            int partId = 0;
            CloudDrivePart cloudDrivePart = new CloudDrivePart();
            cloudDrivePart.parts = new List<PartsItem>();
            foreach (var item in li)
            {
                partId++;
                var res = CloudUpload(item, file.Name, $"{uploadUrl}?partId={partId}").GetAwaiter().GetResult();
                PartsItem partsItem = new PartsItem();
                partsItem.partId = partId;
                cloudDrivePart.parts.Add(partsItem);
            }
            var ss = PutWebRequest($"{uploadUrl}?commit", JsonConvert.SerializeObject(cloudDrivePart));
        }


        private static List<byte[]> LimitedSizeInputStream(FileInfo file, int chunkSize)
        {
            List<byte[]> li = new List<byte[]>();
            using (FileStream fs = file.OpenRead())
            {
                long totalBytesToUpload = fs.Length;

                for (long offset = 0; offset < totalBytesToUpload; offset += chunkSize)
                {
                    byte[] buffer = new byte[chunkSize];
                    fs.Read(buffer, 0, Math.Min((int)(totalBytesToUpload - offset), chunkSize));
                    li.Add(buffer);
                }
                return li;
            }
        }
        public static async Task<FileInfo> getFile(string imagePath,string extention)
        {
            using (var httpClient = new HttpClient())
            {
                var formDataContent = new MultipartFormDataContent();
                byte[] fileBytes = await GetBytesFromUrlAsync(httpClient, imagePath);
                // 设置要保存的文件路径及名称
                string savePath = "";
                try
                {
                    Convert.FromBase64String(imagePath);
                    savePath = "temp"+extention;
                }
                catch (FormatException)
                {
                    savePath = imagePath.Substring(imagePath.ReplaceAll("\\\\", "/").LastIndexOf("/"));
                }
                FileStream fs = new FileStream(savePath, FileMode.Create); // 创建保存文件的流
                fs.Write(fileBytes, 0, fileBytes.Length); // 将文件数据写入到流中
                fs.Close(); // 关闭流
                FileInfo file = new FileInfo(savePath);
                return file;
            }
        }
        static async Task<byte[]> GetBytesFromUrlAsync(HttpClient client, string url)
        {

            if (url.StartsWith("http"))
            {
                var responseMessage = await client.GetAsync(url);

                if (!responseMessage.IsSuccessStatusCode)
                {
                    throw new Exception($"无法访问URL：{url} - HTTP状态码：{responseMessage.StatusCode}");
                }

                return await responseMessage.Content.ReadAsByteArrayAsync();

            }
            else
            {
                try
                {
                    return Convert.FromBase64String(url);
                }
                catch (FormatException)
                {
                    return await File.ReadAllBytesAsync(url);
                }
            }
        }
        #endregion
    }
}
